#ifndef UDP_SERVER
#define UDP_SERVER
#include <iostream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <strings.h>
#include <string>
#include <arpa/inet.h>
#include "Log.hpp"
using namespace std;
using namespace my_log;
class UdpServer
{
public:
    UdpServer(uint16_t port)
        : _socketfd(-1), _port(port)
    {
    }
    void Init()
    {
        // 打开网络文件 IPv4 数据包 udp
        _socketfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_socketfd < 0)
        {
            LOG(Level::ERROR) << "socket() fail";
            exit(1);
        }
        else
        {
            LOG(Level::INFO) << "socket() success _socketfd:" << _socketfd;
        }
        struct sockaddr_in sd;
        bzero(&sd, sizeof(sd));
        sd.sin_family = AF_INET;
        sd.sin_port = htons(_port);
        //sd.sin_addr.s_addr = inet_addr(_ip.c_str());
        sd.sin_addr.s_addr = INADDR_ANY;
        //  绑定ip地址与端口号
        int n = bind(_socketfd, (const sockaddr *)&sd, sizeof(sd));
        if (n < 0)
        {
            LOG(Level::FATAL) << "bind fial";
            exit(1);
        }
        else
        {
            LOG(Level::INFO) << "bind success";
        }
    }
    void Start()
    {
        while (true)
        {
            struct sockaddr_in sd;
            char buffer[1024];
            socklen_t len = sizeof(sd);
            int n = recvfrom(_socketfd, buffer, sizeof(buffer), 0, (sockaddr *)&sd, &len);
            buffer[n] = '\0';
            string peerPort = to_string(ntohs(sd.sin_port));
            string peerIp = inet_ntoa(sd.sin_addr);
            cout << peerIp << '|' <<peerPort << " #: " << buffer << endl;

            string send_message = "Server Say# 已接收";
            sendto(_socketfd, send_message.c_str(), send_message.size(), 0, (const sockaddr *)&sd, len);
        }
    }
    ~UdpServer()
    {
    }

private:
    int _socketfd;
    uint16_t _port;
    //string _ip;
};
#endif